package com.sytech.power_bank.helper

import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import java.nio.charset.Charset

typealias HttpParams=List<Pair<String,Object>>
typealias HttpHeads=List<Pair<String,Object>>
typealias HttpBody=String
fun String.encodeURL(charSet:String="utf-8"):String{
    return URLEncoder.encode(this,charSet)
}
fun HttpParams.getFromURL(url:String, head:HttpHeads= arrayListOf(), timeOut:Int=1000*15, charset: Charset= Charset.forName("utf-8")):String{
    var con=URL("$url?${this.urlParam()}".encodeURL()).openConnection() as HttpURLConnection
    try{
        con.readTimeout=timeOut
        con.requestMethod="GET"
        head.forEach { con.addRequestProperty(it.first,it.second.toString()) }
        return con.inputStream.readBytes().toString(charset)
    }finally {
        con.disconnect()
    }
}
fun HttpParams.urlParam():String{
    return this.joinToString("&"){
        "${it.first}=${it.second.toString().encodeURL()}"
    }
}
fun HttpParams.postToURL(url:String, head:HttpHeads= arrayListOf(),timeOut: Int=1000*15,charset: Charset= Charset.forName("utf-8")):String{
    var con=URL("$url".encodeURL()).openConnection() as HttpURLConnection
    try{
        con.readTimeout=timeOut
        con.requestMethod="POST"
        head.forEach { con.addRequestProperty(it.first,it.second.toString()) }
        con.outputStream.write(this.urlParam().toByteArray(charset))
        return con.inputStream.readBytes().toString(charset)
    }finally {
        con.disconnect()
    }
}
fun HttpBody.postToURL(url:String,head: HttpHeads= arrayListOf(),timeOut: Int=1000*15,charset: Charset= Charset.forName("utf-8")):String{
    var con=URL(url).openConnection() as HttpURLConnection
    try{
        con.readTimeout=timeOut
        con.requestMethod="POST"
        con.doInput=true
        con.doOutput=true
        head.forEach { con.addRequestProperty(it.first,it.second.toString()) }
        con.outputStream.write(this.toByteArray(charset))
        return con.inputStream.readBytes().toString(charset)
    }finally {
        con.disconnect()
    }
}